package com.google.bling.client;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;

public class AddTransactionChannel {
	public static final class Response {
      // Responses are empty
		public Response(JSONObject o) {};
	}

	static final class WrapperCallback implements JavaScriptObjectCallback {
		public WrapperCallback(AddTransactionCallback c) {
			this.c = c;
		}
		public void execute(JavaScriptObject o) {
			this.c.execute(new Response(new JSONObject(o)));
		}
		private AddTransactionCallback c;
	}

	public void request(
			int group_id,
			String participants,  // CSV!
			String title,
			double total,
			String payer,
			String lineString,  // CSV!
			AddTransactionCallback c) {
		request_(group_id, participants, title, total, payer, lineString, new WrapperCallback(c));
	}

	private native void request_(
			int group_id,
			String participants,  // CSV!
			String title,
			double total,
			String payer,
			String lineString,  // CSV!
			JavaScriptObjectCallback c)/*-{
    	// NOTE(appleton): Point this at your real AppEngine instance.  For now we mock.
//    	var requestPath = 'http://www.corp.google.com/~appleton/bling/mock_add_transaction.js';
    	var requestPath = 'http://localhost:8080/transaction/add';
    	// HACK(appleton): mock_add_transaction.js hard-codes this callback name.
    	var callbackName = "myCallbackFunction";

    	// Attach handler to window
    	$wnd[callbackName] = function(o) {
    	    alert("We got called back.");
    		c.@com.google.bling.client.JavaScriptObjectCallback::execute(Lcom/google/gwt/core/client/JavaScriptObject;)(o);
  		};

		// Form request url
		var url = requestPath
			+ '?group_id=' + group_id
			+ '&participants=' + participants
			+ '&title=' + title
			+ '&total=' + total
			+ '&payer=' + payer
			+ '&line=' + lineString
			+ '&callback=' + callbackName;

	    var elem = $doc.createElement('div');
	    elem.innerText = url;
	    $doc.body.appendChild(elem);

		// JSONP request
		var script = $doc.createElement('script');
    	script.type = 'text/javascript';
    	script.src = url;
    	$doc.body.appendChild(script);
  	}-*/;
}
